<template>
  <div class="search-page">
    <!-- 使ios return 按钮变成搜索文本 -->
    <form class="search-header" action="/">
      <van-search
        v-model="value"
        show-action
        placeholder="请输入搜索关键词"
        background="#3296fa"
        @search="onSearch"
        @cancel="onCancel"
        @focus="isResultShow = false"
      />
    </form>

    <!-- 搜索结果 -->
    <search-results :search-text="value" v-if="isResultShow" />
    <!-- 搜索历史 -->
    <search-history @on-search="onSearch" :search-history="history" v-else-if="value === ''" />
    <!-- 搜索建议 -->
    <search-suggestion @on-search="onSearch" :search-text="value" v-else />
  </div>
</template>

<script>
import SearchHistory from './components/search-history.vue'
import SearchResults from './components/search-results.vue'
import SearchSuggestion from './components/search-suggestion.vue'
import { setItem, getItem } from '@/utils/storage.js'
export default {
  name: 'Search',
  data() {
    return {
      value: '', // 输入框双向绑定的数据
      isResultShow: false,
      history: getItem('serach-histories') || [] // 搜索历史
    }
  },

  components: {
    SearchHistory,
    SearchResults,
    SearchSuggestion
  },

  watch: {
    history(val) {
      // 同步到本地存储
      setItem('serach-histories', val)
    }
  },

  created() {

  },

  methods: {
    // 触发搜索
    onSearch(val) {
      this.value = val
      this.history.unshift(val)
      // 将set数组转成普通数组
      this.history = Array.from(new Set(this.history))
      // 显示搜索结果
      this.isResultShow = true
    },
    // 点击取消
    onCancel() {
      this.$router.go(-1)
    }
  }
}
</script>

<style scoped lang='less'>
.search-page {
  .van-search__action {
    color: #fff;
  }

  .search-header {
    position: sticky;
    top: 0;
    z-index: 2;
  }
}
</style>
